package servlets.user;

import hibernate.method.UserMethods;
import hibernate.model.User;
import hibernate.util.HibernateUtil;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

/**
 * Servlet implementation class ChangeType
 */
@WebServlet("/ChangeType")
public class ChangeType extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ChangeType() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		
		
		String user = (String) request.getParameter("user_id");
		int user_id = Integer.parseInt(user);
		String type = (String) request.getParameter("type");
		SessionFactory sessionFactory = HibernateUtil
				.getSessionAnnotationFactory();
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		
		UserMethods um = new UserMethods();
		User editableUser = um.id_to_user(sessionFactory, session, user_id);
		
		editableUser.setType(type);
	
		
		
		 try {
			 session.getTransaction().commit();
				out.println("<script type=\"text/javascript\">alert(\"Zmieniono typ uzytkownika\"); window.location.href = \"admin/index.jsp?page=users&group=users\";</script>");
	    		
	        } catch (Exception ex) {
	            ex.printStackTrace();
	            out.println("<script type=\"text/javascript\">alert(\"Wystapil nieznany blad. Za utrudnienia przepraszamy\"); window.location.href = \"admin/index.jsp?page=users&group=users\";</script>");
	    		
	        } 
		 }
	

}
